package algorithm;

import java.util.Arrays;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author 刘正星
 * @version 1.0.0
 * @ClassName BinarySearch.java
 * @Description TODO
 * @createTime 2021年02月20日 22:37:00
 */
public class BinarySearch {
    public static int BinarySearch(Integer[] array, int aim) {
        int low = 0;
        int high = array.length - 1;
        while (low <= high) {
            int mid = (low + high) / 2;
            int guess = array[mid];
            if (guess == aim) {
                return mid;
            } else if (guess > aim) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }

        }
        return -1;
    }

    public static void main(String[] args) {
        Random random = new Random();
        Integer[] array1 = {1, 2, 5, 6, 7, 20, 30, 45};
//        Integer [] array =  random.ints(10,1,11).boxed().peek(System.out::println).toArray(Integer[]::new);
//        Arrays.sort(array);
//        Stream.of(array).forEach(System.out::println);
        int result = BinarySearch(array1, 5);
        System.out.println(result);
    }
}
